from hashlib import md5
from django.http import HttpResponse
from django.http import HttpRequest
import json
import datetime
import random

from Response.Resp import Resp
from Model.models import User
from Model.models import MailCode
from utils.mail import MailSender
from Model.models import AccessRecords


'''
class of User View
'''


class UserView(object):
    def GenerateRandomCode(self) -> str:
        rand_list = random.sample('0123456789', 6)
        code = ""
        for ch in rand_list:
            code += ch
        return code

    '''注册'''
    @classmethod
    def Register(self, request: HttpRequest) -> HttpResponse:
        try:
            if request.method == 'GET':
                pass
            elif request.method == 'POST':
                json_data = json.loads(request.body)
                email = json_data['email']          # 注册所输入的邮件
                check_code = json_data['code']      # 验证码
                pwd = json_data['pwd']              # 密码

                resp_json_data = None

                time_now = datetime.datetime.now() - datetime.timedelta(minutes=10)
                if len(User.objects.filter(email=email)):
                    # 该邮箱已经被注册了
                    resp_json_data = {
                        'hasreg': True,
                        'msg': '该邮箱已注册',
                        'rescode': 400
                    }
                elif len(MailCode.objects.filter(email=email, code=check_code, update_at__gte=time_now)) == 0:
                    # 验证码错误或者超时
                    resp_json_data = {
                        'hasreg': False,
                        'msg': '验证码错误或者超时',
                        'rescode': 400
                    }
                else:
                    # 可以注册的状态 在user表中创建该条记录
                    User.objects.create(
                        email=email,
                        pwd=pwd,
                    )
                    # 在验证码表中删除该邮件的记录
                    MailCode.objects.filter(email=email).delete()

                    # 只要注册了就为这个人在测评记录表里面创建一条记录
                    user = User.objects.get(email=email)
                    AccessRecords.objects.create(
                        uid = user,
                    )

                    resp_json_data = {
                        'hasreg': True,
                        'reg': True,
                        'rescode': 200,
                        'msg': '注册成功'
                    }
                return Resp.RightResp(resp_json_data)
        except Exception as e:
            print(repr(e))
            return Resp.ErrorResp({
                'rescode': 400,
                'msg': str(e)
            })

    ''' 
    登录
    '''
    @classmethod
    def Login(self, request: HttpRequest) -> HttpResponse:
        try:
            if request.method == 'GET':
                pass
            elif request.method == 'POST':
                resp_json_data = None
                json_data = json.loads(request.body)
                email = json_data['email']
                pwd = json_data['pwd']
                # 去mysql中查询是否有匹配的邮箱地址和密码
                result = User.objects.filter(
                    email=email, pwd=pwd
                )

                if len(result) == 0:
                    resp_json_data = {
                        'loginin': False,
                        'msg': '邮箱或者密码错误',
                        'rescode': 400
                    }
                else:
                    uid = result[0].id
                    name = result[0].name
                    resp_json_data = {
                        'loginin': True,
                        'uid': uid,
                        'email': email,
                        'name': name,
                        'msg': '登录成功',
                        'rescode': 200
                    }
                return Resp.RightResp(resp_json_data)
        except Exception as e:
            print(repr(e))
            return Resp.ErrorResp({
                'rescode': 400,
                'msg': str(e)
            }, 500)

    '''
    忘记密码的找回
    '''
    @classmethod
    def ForgetPwd(self, request: HttpRequest) -> HttpResponse:
        try:
            if request.method == 'GET':
                pass
            elif request.method == 'POST':
                json_data = json.loads(request.body)
                email = json_data['email']
                # 从mysql中查询该用户，根据邮箱
                user_list = User.objects.filter(email=email)
                if len(user_list) == 0:
                    return Resp.RightResp({
                        'msg': '该邮箱未注册',
                        'rescode': 500
                    })
                else:
                    # 随机生成新的密码通过邮箱发送给用户
                    new_pwd = self.GenerateRandomCode(self)
                    now_user = user_list[0]
                    now_user.pwd = md5((new_pwd).encode('utf-8')).hexdigest()
                    now_user.save()
                    # 发送验证码
                    email_res = MailSender.SendPwd(email, new_pwd)
                    if email_res == True:
                        return Resp.RightResp({'rescode': 200})
                    else:
                        return Resp.RightResp({'rescode': 400})
        except Exception as e:
            print(repr(e))
            return Resp.ErrorResp({
                'rescode': 400,
                'msg': str(e)
            }, 401)

    ''' 
    重置密码
    '''
    @classmethod
    def ResetPwd(self, request: HttpRequest) -> HttpResponse:
        try:
            if request.method == 'GET':
                pass
            elif request.method == 'POST':
                json_data = json.loads(request.body)
                email = json_data['email']
                old_pwd = json_data['oldpwd']
                new_pwd = json_data['newpwd']

                # 从mysql中查询该用户，根据邮箱
                now_user = User.objects.get(email=email)

                if now_user.pwd != old_pwd:
                    resp_json_data = {
                        'msg': '原密码错误',
                        'rescode': 400
                    }
                else:
                    now_user.pwd = new_pwd
                    now_user.save()
                    resp_json_data = {
                        'msg': '修改密码成功',
                        'rescode': 200
                    }
                return Resp.RightResp(resp_json_data)
        except Exception as e:
            print(repr(e))
            return Resp.ErrorResp({
                'rescode': 400,
                'msg': str(e)
            }, 401)

    '''
    退出登录，就清除session就好了
    '''
    @classmethod
    def LoginOut(self, request: HttpRequest) -> HttpResponse:
        # request.session.clear()  # 删除session里的全部内容
        resp_json_data = {
            'loginout': True,
            'rescode': 200
        }
        return Resp.RightResp(resp_json_data)

    """
    发送邮件验证码
    """
    @classmethod
    def SendMail(self, request: HttpRequest) -> HttpResponse:
        try:
            if request.method == 'GET':
                pass
            elif request.method == 'POST':
                json_data = json.loads(request.body)
                email = json_data['email']
                # 发送验证码
                email_res = MailSender.SendCheckCode(email)

                resp_json_data = {
                    'send': True,
                    'rescode': 200
                }
                if email_res[1] == True:
                    # 将记录保存到SQL
                    MailCode.objects.create(email=email, code=email_res[0])
                    return Resp.RightResp(resp_json_data)
                else:
                    resp_json_data['send'] = False
                    resp_json_data['rescode'] = 400
                    return Resp.RightResp(resp_json_data)
        except Exception as e:
            print(repr(e))
            return Resp.ErrorResp({
                'rescode': 400,
                'msg': str(e)
            }, 401)